/**
 * 商品详情管理
 */
class ProductDetail {
  constructor() {
    this.productId = new URLSearchParams(window.location.search).get('id');
    this.init();
  }
  
  init() {
    if (this.productId) {
      this.loadProduct();
      this.bindEvents();
    }
  }
  
  loadProduct() {
    // 模拟从API获取单个商品数据
    fetch('api/products.json')
      .then(response => response.json())
      .then(products => {
        const product = products.find(p => p.id == this.productId);
        if (product) {
          this.renderProduct(product);
        } else {
          document.getElementById('product-detail').innerHTML = '<div class="error">商品不存在</div>';
        }
      });
  }
  
  renderProduct(product) {
    const container = document.getElementById('product-detail');
    container.innerHTML = `
      <div class="product-images">
        <div class="main-image">
          <img src="${product.image}" alt="${product.name}">
        </div>
        <div class="thumbnails">
          ${product.images ? product.images.map(img => `
            <img src="${img}" alt="${product.name}">
          `).join('') : ''}
        </div>
      </div>
      <div class="product-info">
        <h1>${product.name}</h1>
        <div class="price-section">
          <span class="current-price">¥${product.price.toFixed(2)}</span>
          ${product.originalPrice ? `<span class="original-price">¥${product.originalPrice.toFixed(2)}</span>` : ''}
        </div>
        <div class="rating">
          ${this.renderRating(product.rating || 0)}
          <span class="review-count">${product.reviews || 0}条评价</span>
        </div>
        <div class="product-meta">
          <div class="meta-item">
            <span class="label">品牌</span>
            <span class="value">${product.brand || '未知'}</span>
          </div>
          <div class="meta-item">
            <span class="label">库存</span>
            <span class="value">${product.stock || 0}件</span>
          </div>
        </div>
        <div class="product-actions">
          <div class="quantity-selector">
            <button class="decrease">-</button>
            <input type="number" value="1" min="1" max="${product.stock || 10}">
            <button class="increase">+</button>
          </div>
          <button class="add-to-cart">加入购物车</button>
          <button class="buy-now">立即购买</button>
        </div>
      </div>
      <div class="product-tabs">
        <div class="tabs-header">
          <button class="tab-btn active" data-tab="description">商品详情</button>
          <button class="tab-btn" data-tab="specs">规格参数</button>
          <button class="tab-btn" data-tab="reviews">用户评价</button>
        </div>
        <div class="tabs-content">
          <div class="tab-pane active" id="description">
            ${product.description || '暂无商品描述'}
          </div>
          <div class="tab-pane" id="specs">
            ${product.specs ? `
              <table class="specs-table">
                ${Object.entries(product.specs).map(([key, value]) => `
                  <tr>
                    <th>${key}</th>
                    <td>${value}</td>
                  </tr>
                `).join('')}
              </table>
            ` : '暂无规格参数'}
          </div>
          <div class="tab-pane" id="reviews">
            ${product.reviewsList ? this.renderReviews(product.reviewsList) : '暂无用户评价'}
          </div>
        </div>
      </div>
    `;
  }
  
  renderRating(rating) {
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 >= 0.5;
    let stars = '';
    
    for (let i = 1; i <= 5; i++) {
      if (i <= fullStars) {
        stars += '<i class="fas fa-star"></i>';
      } else if (i === fullStars + 1 && hasHalfStar) {
        stars += '<i class="fas fa-star-half-alt"></i>';
      } else {
        stars += '<i class="far fa-star"></i>';
      }
    }
    
    return stars;
  }
  
  renderReviews(reviews) {
    return reviews.map(review => `
      <div class="review-item">
        <div class="review-header">
          <span class="user">${review.user}</span>
          <span class="rating">${this.renderRating(review.rating)}</span>
          <span class="date">${review.date}</span>
        </div>
        <div class="review-content">
          <h4>${review.title}</h4>
          <p>${review.content}</p>
        </div>
      </div>
    `).join('');
  }
  
  bindEvents() {
    const container = document.getElementById('product-detail');
    if (!container) return;
    
    // 缩略图点击事件
    container.addEventListener('click', (e) => {
      if (e.target.closest('.thumbnails img')) {
        const mainImg = container.querySelector('.main-image img');
        mainImg.src = e.target.src;
      }
      
      // 数量增减
      if (e.target.classList.contains('increase')) {
        const input = e.target.previousElementSibling;
        input.stepUp();
      } else if (e.target.classList.contains('decrease')) {
        const input = e.target.nextElementSibling;
        input.stepDown();
      }
      
      // 标签切换
      if (e.target.classList.contains('tab-btn')) {
        const tabId = e.target.dataset.tab;
        container.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
        container.querySelectorAll('.tab-pane').forEach(pane => pane.classList.remove('active'));
        e.target.classList.add('active');
        document.getElementById(tabId).classList.add('active');
      }
      
      // 加入购物车
      if (e.target.classList.contains('add-to-cart')) {
        const quantity = parseInt(container.querySelector('.quantity-selector input').value);
        this.addToCart(quantity);
      }
      
      // 立即购买
      if (e.target.classList.contains('buy-now')) {
        const quantity = parseInt(container.querySelector('.quantity-selector input').value);
        this.buyNow(quantity);
      }
    });
  }
  
  addToCart(quantity) {
    // 模拟获取当前商品
    fetch('api/products.json')
      .then(response => response.json())
      .then(products => {
        const product = products.find(p => p.id == this.productId);
        if (product) {
          const cart = JSON.parse(localStorage.getItem('cart')) || [];
          const existingItem = cart.find(item => item.id == product.id);
          
          if (existingItem) {
            existingItem.quantity += quantity;
          } else {
            cart.push({...product, quantity});
          }
          
          localStorage.setItem('cart', JSON.stringify(cart));
          alert('商品已添加到购物车');
          
          // 更新购物车数量
          if (window.vipShop) {
            window.vipShop.updateCartCount();
          }
        }
      });
  }
  
  buyNow(quantity) {
    // 模拟获取当前商品
    fetch('api/products.json')
      .then(response => response.json())
      .then(products => {
        const product = products.find(p => p.id == this.productId);
        if (product) {
          // 直接创建订单
          const order = {
            id: Date.now(),
            date: new Date().toISOString(),
            items: [{...product, quantity}],
            total: product.price * quantity,
            status: '待付款'
          };
          
          // 保存订单
          const orders = JSON.parse(localStorage.getItem('orders')) || [];
          orders.push(order);
          localStorage.setItem('orders', JSON.stringify(orders));
          
          // 跳转到订单页面
          window.location.href = `order.html?orderId=${order.id}`;
        }
      });
  }
}

// 初始化商品详情
document.addEventListener('DOMContentLoaded', () => {
  if (document.getElementById('product-detail')) {
    new ProductDetail();
  }
});